package com.ylbh.common.utils;

import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
* OSS图片服务器工具类
* @Description:
* @Date: Created in 2018/6/4 13:39
* @Author: Wangll
*/

@Component
public class OSSClient {
//private final Logger logger = LoggerFactory.getLogger(BankServiceImpl.class);

    /**
     * 北京 = oss-cn-beijing.aliyuncs.com
     *
     */
    private String endPoint = "oss-cn-shenzhen.aliyuncs.com";

    /**
     * zhonglin的：LTAId9fnRGDJvjx5    yrJOQq1UuTs1gR9GHRL6EZLNcgO1AQ
     *
     *LTAIwSynClEKZSWc 是 songbei1538的
     */
    private String accessKeyId = "LTAIwSynClEKZSWc";

    private String accessKeySecret = "k9JCzDEVi39tMFO6MIq88XujeWtTKw";

    /**
     * 空间
     */
    private String bucketName = "app-songbei";

/**
* 文件存储目录
*/
//private String filedir = "business/";


private com.aliyun.oss.OSSClient ossClient;

public OSSClient() {
ossClient = new com.aliyun.oss.OSSClient(endPoint, accessKeyId, accessKeySecret);
}
/**
* 初始化
*/
public void init() {
ossClient = new com.aliyun.oss.OSSClient(endPoint, accessKeyId, accessKeySecret);
}
/**
* 销毁
*/
public void destory() {
ossClient.shutdown();
}

/**
* 上传本地图片
*
*/
public String uploadImg2Oss(String url,String filedir, String modeName)  {
File fileOnServer = new File(url);
FileInputStream fin;
try {
    fin = new FileInputStream(fileOnServer);
    String[] split = url.split("/");
    this.init();
    String fileUrl =this.uploadFile2OSS(fin,filedir, split[split.length - 1], modeName);
    this.destory();
    return fileUrl;//1539613128619.jpg
} catch (FileNotFoundException e) {
    return "fail";
}
}


    /**
     * 压缩后上传本地图片
     *
     */
    public String uploadCompressImg2Oss(MultipartFile file,String filedir, String modeName)  {
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();

        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            Thumbnails.of(file.getInputStream()).scale(1f).outputFormat("jpg").outputQuality(0.8).toOutputStream(byteArrayOutputStream);
//            Thumbnails.of(file.getInputStream()).scale(1f).outputFormat("jpg").outputQuality(0.8).toFile(new File(file.getOriginalFilename()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream fin = null;
        try {
            fin = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
//            fin = file.getInputStream();
            this.init();
            String fileUrl =this.uploadFile2OSS(fin,filedir, substring, modeName);
            this.destory();
            return fileUrl;//1539613128619.jpg
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
        finally {
//            new File(file.getOriginalFilename()).delete();
            if(fin != null){
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

/**
* 上传图片到服务器
*
*/
public String uploadImg2Oss(MultipartFile file, String filedir, String modeName)  {

if (file.getSize() > 1024 * 1024 * 10) {
    return "上传图片大小不能超过10M！";
}
String originalFilename = file.getOriginalFilename();
String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
try {
    InputStream inputStream = file.getInputStream();
    this.init();
    String url =this.uploadFile2OSS(inputStream,filedir, substring, modeName);
    this.destory();
    return url;//文件名称
} catch (Exception e) {
    return "fail";
}
}

    /**
     * 上传视频到服务器
     *
     */
    public String uploadVideo2Oss(MultipartFile file, String filedir, String modeName)  {

        if (file.getSize() > 1024 * 1024 * 10) {
            return "上传视频大小不能超过10M！";
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        try {
            InputStream inputStream = file.getInputStream();
            this.init();
            String url =this.uploadFile2OSS(inputStream,filedir, substring, modeName);
            this.destory();
            return url;//文件名称
        } catch (Exception e) {
            return "fail";
        }
    }

/**
* 上传多张图片图片到服务器
*
*/
public String uploadImg2Oss(List<MultipartFile> files, String filedir, String modeName){
String url;
StringBuffer sb = new StringBuffer();
this.init();
for (MultipartFile file : files) {
    if (file.getSize() > 1024 * 1024 * 10) {
        System.out.println("上传图片大小不能超过10M！");
        return "上传图片大小不能超过10M！";
    }
    String originalFilename = file.getOriginalFilename();
    String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
    try {
        InputStream inputStream = file.getInputStream();
        url =this.uploadFile2OSS(inputStream,filedir, substring, modeName);
        sb.append(url).append(",");
    } catch (Exception e) {

        return "fail";
    }
}
this.destory();
sb = sb.deleteCharAt(sb.length() - 1);
return sb.toString();
}


/**
* 获得图片路径
*
* @param fileUrl
* @return
*/
public String getImgUrl(String filedir,String fileUrl) {
if (!StringUtils.isEmpty(fileUrl)) {
    String[] split = fileUrl.split("/");
    this.init();
    String str = this.getUrl(filedir + split[split.length - 1]);
    this.destory();
    return str;
}
return null;
}

/**
* 上传到OSS服务器  如果同名文件会覆盖服务器上的
*
* @param instream 文件流
* @param fileName 文件名称 包括后缀名
* @return 出错返回"" ,唯一MD5数字签名
*/
public String uploadFile2OSS(InputStream instream,String filedir, String fileName, String modeName) {
this.init();
String ret = "";
try {
    //创建上传Object的Metadata
    ObjectMetadata objectMetadata = new ObjectMetadata();
    objectMetadata.setContentLength(instream.available());
    objectMetadata.setCacheControl("no-cache");
    objectMetadata.setHeader("Pragma", "no-cache");
    objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
    objectMetadata.setContentDisposition("inline;filename=" + fileName);
    String substring = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
    Random random = new Random();
    fileName = random.nextInt(10000) + System.currentTimeMillis() + substring;
    //上传文件
    PutObjectResult putResult = ossClient.putObject(bucketName, filedir + modeName + "/" + fileName, instream, objectMetadata);
    System.out.println("putResult = " + putResult);
    return fileName;
}catch(Exception e){
    return "fail";
} finally {
    this.destory();
    try {
        if (instream != null) {
            instream.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

/**
* Description: 判断OSS服务文件上传时文件的contentType
*
* @param FilenameExtension 文件后缀
* @return String
*/
public static String getcontentType(String FilenameExtension) {
if (FilenameExtension.equalsIgnoreCase(".bmp")) {
    return "image/bmp";
}
if (FilenameExtension.equalsIgnoreCase(".gif")) {
    return "image/gif";
}
if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
        FilenameExtension.equalsIgnoreCase(".jpg") ||
        FilenameExtension.equalsIgnoreCase(".png")) {
    return "image/jpeg";
}
if (FilenameExtension.equalsIgnoreCase(".html")) {
    return "text/html";
}
if (FilenameExtension.equalsIgnoreCase(".txt")) {
    return "text/plain";
}
if (FilenameExtension.equalsIgnoreCase(".vsd")) {
    return "application/vnd.visio";
}
if (FilenameExtension.equalsIgnoreCase(".pptx") ||
        FilenameExtension.equalsIgnoreCase(".ppt")) {
    return "application/vnd.ms-powerpoint";
}
if (FilenameExtension.equalsIgnoreCase(".docx") ||
        FilenameExtension.equalsIgnoreCase(".doc")) {
    return "application/msword";
}
if (FilenameExtension.equalsIgnoreCase(".xml")) {
    return "text/xml";
}
if (FilenameExtension.equals(".mp4") || FilenameExtension.equals(".MP4")) {
    return "video/mp4";
}
return "image/jpeg";
}

/**
* 获得url链接
*
*/
public String getUrl(String key) {
// 设置URL过期时间为10年  3600l* 1000*24*365*10
Date expiration = new Date(System.currentTimeMillis() + 3600l * 1000 * 24 * 365 * 10);
// 生成URL
this.init();
URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
if (url != null) {
    return url.toString();
}
this.destory();
return null;
}

}
